const { JSDOM } = require("jsdom");

const indexForm39 = ({ res, response }) => {
  res.setHeader("Content-Type", "application/json");
  try {
    console.log(response);
    const dom = new JSDOM(response);
    const document = dom.window.document;
    const list = [];

    const domList = [...document.querySelectorAll(".tuanlistbox")];

    domList.forEach((card) => {
      const cardInfo = card.textContent
        .replace(/\s{2,}/g, "  ")
        .split("  ")
        .filter((text) => text !== "");
      const id = card.querySelector("a").href.split("Id=")[1];
      const img = card.querySelector("img").src;

      list.push({
        id,
        title: cardInfo[0],
        desc: cardInfo.slice(1),
        img,
      });
    });

    return JSON.stringify({
      data: list,
      success: true,
    });
  } catch (error) {
    return JSON.stringify({
      success: false,
    });
  }
};

module.exports = {
  indexForm39,
};
